#include "PreCompile.h"
#include "AsyncSelect.h"
#include "MsgSink.h"
#include "Frame.h"


using namespace std;

CAsyncSelect::CAsyncSelect():m_socket(INVALID_SOCKET)
{
}

bool CAsyncSelect::Initialize()
{
	WSADATA wsaData;
	int res = 0;
	res = WSAStartup(MAKEWORD(2, 2), &wsaData);
	if(res)
	{
		DisplayError(res);
		return false;
	}

	m_socket = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, 0, 0, 0);
	if(m_socket == INVALID_SOCKET)
	{
		DisplayError(WSAGetLastError());
		return false;
	}

	if(WSAAsyncSelect(m_socket, *CFrame::Get(), WM_SOCKET, FD_CONNECT | FD_WRITE | FD_CLOSE | FD_READ))
	{
		DisplayError(WSAGetLastError());
		return false;
	}
	return true;
}

bool CAsyncSelect::Send(const void* buf, int len)
{
	return true;
}

bool CAsyncSelect::Connect(const char* addr, unsigned short port)
{
	sockaddr_in serverAddr;
	serverAddr.sin_addr.s_addr = inet_addr(addr);
	serverAddr.sin_family = AF_INET;
	serverAddr.sin_port = htons(port);
	WSAConnect(m_socket, (sockaddr*)&serverAddr, sizeof(serverAddr), 0, 0, 0, 0);
	if(WSAGetLastError() != WSAEWOULDBLOCK)
	{
		DisplayError(WSAGetLastError());
		return false;
	}
	return true;
}

void CAsyncSelect::Close()
{
	closesocket(m_socket);
}
